const auth = require('../middlewares/auth')
const Router = require('koa-router')
const validate = require('../utils/verify')
const { ValidationError } = require('../utils/customError')
const Categorys = require('../models/Categorys')
const { literal } = require('../config/db')
const Post = require('../models/Post')
const { Op } = require('sequelize')
const { categoryList } = require('../attributes/category')
const router = new Router()

router.prefix('/category')
router['get']('/list', async (ctx) => {
  // 获取请求头参数
  const { requesttype } = ctx.request.header
  let { page, pageSize, key } = ctx.query

  let where = {}
  let countWhere = 'WHERE posts.categoryId = categorys.id AND posts.deletedAt IS NULL'
  if (key) {
    where.name = {
      [Op.like]: `%${key}%`,
    }
  }
  let categoryIds = []
  if (requesttype !== 'admin') {
    where.status = {
      [Op.ne]: 'N',
    }
    countWhere = `WHERE posts.categoryId = categorys.id AND posts.status = 'published' AND posts.deletedAt IS NULL`
  } else {
    if (page && pageSize) {
      // 计算分页
      const offset = (parseInt(page) - 1) * parseInt(pageSize)
      categoryIds = await Categorys.findAll({
        attributes: ['id'],
        where,
        group: 'id',
        limit: Number.parseInt(pageSize, 10), // 使用 Number.parseInt 确保有效数字
        offset: offset,
        raw: true,
      })
      where = {
        id: categoryIds.length ? categoryIds.map((item) => item.id) : [],
        ...where,
      }
    }
  }
  // 分页查询全部分类列表
  const result = await Categorys.findAll({
    attributes: [
      ...categoryList,
      [
        literal(`(
      SELECT COUNT(*) 
      FROM posts ${countWhere}
    )`),
        'articleCount',
      ], // 计算文章数
    ],
    include: [
      {
        model: Post,
        as: 'posts',
        attributes: [], // 不返回 Post 的具体字段
        required: false, // LEFT JOIN
      },
    ],
    where,
    group: ['categorys.id'], // GROUP BY
    raw: true, // 直接返回纯数据（可选）
  })
  // 获取符合条件的总数
  const total = await Categorys.count(where)
  ctx.body = {
    code: 200,
    data: { total, result },
  }
})
// 创建分类
router['post']('/create', auth, async (ctx) => {
  const data = ctx.request.body
  if (validate.isEmpty(data.name)) {
    return (ctx.body = {
      code: 422,
      data: { message: '分类名字不能是空的' },
    })
  }
  const result = await Categorys.create(data)
  if (!result) {
    throw new Error('分类创建失败')
  }
  ctx.body = {
    code: 200,
    data: true,
  }
})
// 更新分类
router['post']('/update', auth, async (ctx) => {
  const data = ctx.request.body
  if (validate.isEmpty(String(data.id))) {
    return (ctx.body = {
      code: 422,
      data: { message: '分类id不能是空的' },
    })
  }
  if (validate.isEmpty(data.name)) {
    return (ctx.body = {
      code: 422,
      data: { message: '分类名字不能是空的' },
    })
  }
  const result = await Categorys.update(data, {
    where: {
      id: data.id,
    },
  })
  if (!result) {
    throw new Error('分类更新失败')
  }
  ctx.body = {
    code: 200,
    data: true,
  }
})
// 删除分类
router['post']('/delete', auth, async (ctx) => {
  const { id } = ctx.request.body
  if (!id) {
    return (ctx.body = {
      code: 422,
      data: { message: '分类id不能是空的' },
    })
  }
  try {
    const result = await Categorys.destroy({
      where: { id },
    })
    // 同时把对应文章的分类id置为null
    await Post.update(
      {
        categoryId: null,
      },
      {
        where: {
          categoryId: id,
        },
      },
    )
    if (result) {
      ctx.body = {
        code: 200,
        data: true,
      }
    }
  } catch (e) {
    return (ctx.body = {
      code: 500,
      data: { message: e.message },
    })
  }
})
// #TODO 获取分类下的文章
router['get']('/detail', async (ctx) => {
  const { id, page = 1, pageSize = 10, sort = '' } = ctx.query
  if (!id) {
    return (ctx.body = {
      code: 422,
      data: { message: '分类id不能是空的' },
    })
  }
  const offset = (parseInt(page) - 1) * parseInt(pageSize)
  const order = []
  if (sort === 'latest') {
    order.push(['createdAt', 'DESC'])
  }
  if (sort === 'popular') {
    // 查询最多阅读量
    ;[
      literal(`(
        SELECT COUNT(*)
        FROM views
        WHERE views.postId = posts.id
      )`),
      'DESC',
    ]
  }
  const result = await Post.findAndCountAll({
    where: { categoryId: id, status: 'published' },
    attributes: [
      'id',
      'title',
      'createdAt',
      'coverImage',
      'likes',
      'excerpt',
      'categoryId',
      [
        literal(`(SELECT COUNT(*) FROM categorys WHERE categorys.id = posts.categoryId)`),
        'categoryName',
      ],
      [literal(`(SELECT COUNT(*) FROM views WHERE views.postId = posts.id)`), 'views'],
    ],
    order,
    raw: true,
    limit: Number.parseInt(pageSize, 10), // 使用 Number.parseInt 确保有效数字
    offset: offset,
  })
  if (!result) {
    throw new Error('获取分类下的文章失败')
  }
  ctx.body = {
    code: 200,
    data: result,
  }
})
module.exports = router
